<template>
  <m-window-frame
    :title="$t('创建表格')"
    style="height: 100%"
    :okLoading="saveLoading"
    class="v-create-table-wizard"
    @cancel="handleCancel"
  >
    <div class="create-table-wizard-container">
      <AttrTips
        class="_main-title g-flex-0"
        :propertyGroupConfig="attrInfo"
        :type="''"
        background-image="statics/arch/theme/addtitlebg.png"
      ></AttrTips>
      <Step
        v-model="activeKey"
        :steps="steps"
        @stepValueChange="stepValueChange"
      ></Step>
    </div>
    <template v-slot:footer-right>
      <el-button
        size="small"
        :disabled="prevStepDisabled"
        @click="updateStep(-1)"
      >
        {{ "< " + $t("上一步") }}
      </el-button>
      <el-button
        size="small"
        :disabled="nextStepDisabled"
        @click="updateStep(1)"
      >
        {{ $t("下一步") + " >" }}
      </el-button>
      <el-button
        type="primary"
        size="small"
        :loading="saveLoading"
        :disabled="okDisabled"
        @click="handleSave"
      >
        {{ $t("完 成") }}
      </el-button>
      <el-button
        size="small"
        @click="handleCancel"
      >
        {{ $t("取 消") }}
      </el-button>
    </template>
  </m-window-frame>
</template>
<script lang="ts" setup>
import MWindowFrame from "@/common/ipcWindow/WindowFrame.vue";
import AttrTips from "@/common/attrTip/AttrTip.vue";
import Step, { type StepItem } from "./Step.vue";
import { ref, computed, watch, markRaw } from "vue";
import { Params, CloseData } from "./index";
import { useRoute } from "vue-router";
import { ipcWindowUtil } from "@/mdesign-lib/mdesign-app.umd.js";
import TreeSelect from "@/modules/model/modals/modelTreeSelect/components/TreeSelect.vue";
import { PropertyDataType } from "@/mdesign-lib/mdesign-app.umd.js";
import SelectTableOwner from "./steps/SelectTableOwner.vue";
import { toMap } from "@/util/common";
import DateAndTimeSetting from "../dateAndTimeSettingWindow/DateAndTimeSetting.vue";
import { archService } from "@/mdesign-lib/mdesign-app.umd.js";
import { StepParam } from "@/modules/model/comps/station/graphTabs/diagramTableNew/config/toolBar";

interface AttrInfo {
  name: string;
  description: string;
  icon: string;
}

const saveLoading = ref(false);
let projectId = "";
let stereotype = "";
let defaultTableName = "";
let defaultOwnerId = "";
const result = {};
let stepKeys: string[] = [];
let stepParams: Record<string, StepParam> = {};
let disableStepKey: string[] = [];
const route = useRoute();

watch(
  () => route.fullPath,
  () => {
    const routeQuery = route.query as unknown;
    const query = routeQuery as Params;
    projectId = query.projectId;
    stereotype = query.stereotype;
    defaultTableName = query.defaultTableName;
    defaultOwnerId = query.defaultOwnerId;
    stepKeys = query.stepKeys;
    disableStepKey = query.disableStepKey || [];
    stepParams = JSON.parse(query.stepParams) as Record<string, StepParam>;
  },
  { immediate: true }
);

const allSteps: StepItem[] = [
  {
    key: "chooseOwner",
    name: "设置表格名称和所属包",
    description: "设置表格名称并选择一个包作为表格的所有者",
    component: markRaw(SelectTableOwner),
    nextStepDisabled: true,
    params: {
      loadMethod: "getPropertyTreeList",
      loadParams: {
        row: {
          dataType: PropertyDataType.INSTANCE,
          key: "",
          checkMethod: stepParams["chooseOwner"]?.checkMethod,
          modelId: stereotype
        },
        projectId
      },
      stereotype,
      multiple: false,
      showNodeLabel: true,
      defaultCurTab: "list",
      defaultSelectedId: defaultOwnerId,
      defaultTableName
    }
  },
  {
    key: "chooseActualEnterprisePhase",
    name: "选择实际战略阶段",
    description: "选择实际战略阶段",
    component: markRaw(TreeSelect),
    dataType: stepParams["chooseActualEnterprisePhase"]?.dataType,
    params: {
      loadMethod: "getPropertyTreeList",
      loadParams: {
        row: {
          dataType: PropertyDataType.INSTANCE,
          key: "",
          checkMethod: stepParams["chooseActualEnterprisePhase"]?.checkMethod,
          modelId: stereotype
        },
        projectId
      },
      multiple: stepParams["chooseActualEnterprisePhase"]?.multiple === undefined ? true : false,
      showNodeLabel: true,
      defaultCurTab: "list"
    }
  },
  {
    key: "chooseResource",
    name: "选择资源",
    description: "选择资源",
    component: markRaw(TreeSelect),
    params: {
      loadMethod: "getPropertyTreeList",
      loadParams: {
        row: {
          dataType: PropertyDataType.INSTANCE,
          key: "",
          modelId: stereotype,
          checkMethod: stepParams["chooseResource"]?.checkMethod
        },
        projectId
      },
      multiple: true,
      showNodeLabel: true,
      defaultCurTab: "list"
    }
  },
  {
    key: "chooseCapabilities",
    name: "选择能力",
    description: "选择能力",
    component: markRaw(TreeSelect),
    params: {
      loadMethod: "getPropertyTreeList",
      loadParams: {
        row: {
          dataType: PropertyDataType.INSTANCE,
          key: "",
          modelId: stereotype,
          moreBtnCondition: stepParams["chooseCapabilities"]?.moreBtnCondition
        },
        projectId
      },
      multiple: true,
      showNodeLabel: true,
      defaultCurTab: "list"
    }
  },
  {
    key: "chooseActualResponsibleResources",
    name: "选择实际负责资源",
    description: "选择实际负责资源",
    component: markRaw(TreeSelect),
    params: {
      loadMethod: "getPropertyTreeList",
      loadParams: {
        row: {
          dataType: PropertyDataType.INSTANCE,
          key: "",
          modelId: stereotype,
          moreBtnCondition: stepParams["chooseActualResponsibleResources"]?.moreBtnCondition
        },
        projectId
      },
      multiple: true,
      showNodeLabel: true,
      defaultCurTab: "list"
    }
  },
  {
    key: "chooseStartDate",
    name: "设置开始时间",
    description: "设置开始时间",
    component: markRaw(DateAndTimeSetting),
    nextStepDisabled: false,
    params: {
      projectId,
      defaultDate: ""
    }
  },
  {
    key: "chooseEndDate",
    name: "设置结束时间",
    description: "设置结束时间，结束时间需在开始时间之后",
    nextStepDisabled: false,
    component: markRaw(DateAndTimeSetting),
    params: {
      projectId,
      defaultDate: ""
    }
  }
];

const allStepMap = toMap(allSteps, "key");
const steps = ref<StepItem[]>(
  stepKeys
    .map(key => {
      const data = allStepMap.get(key) as StepItem;
      const params = stepParams[key];
      if (params) {
        data.nextStepDisabledKeys = params.nextStepDisabledKeys;
        data.valueName = params.valueName;
      }
      if (disableStepKey.includes(key)) {
        data.disabled = true;
      }
      return data;
    })
    .filter(Boolean) as StepItem[]
);
const activeKey = ref(steps.value[0].key);

const activeStep = computed(() => {
  return steps.value.filter(step => step.key === activeKey.value)[0];
});

const okDisabled = computed(() => {
  return activeStep.value.nextStepDisabled;
});

const attrInfo = computed<AttrInfo>(() => {
  return {
    name: activeStep.value.name as string,
    description: activeStep.value.description as string,
    icon: "statics/icons/attrTip/checkbox.svg"
  };
});

const currentStepIndex = computed(() => {
  return steps.value.findIndex(step => step.key === activeKey.value);
});

const prevStepDisabled = computed(() => {
  const prevSteps = steps.value.slice(0, currentStepIndex.value);
  return prevSteps.every(step => step.disabled);
});

const nextStepDisabled = computed(() => {
  const nextSteps = steps.value.slice(currentStepIndex.value + 1, steps.value.length);
  return nextSteps.every(step => step.disabled) || steps.value[currentStepIndex.value].nextStepDisabled;
});

const getStepByKey = (key: string) => {
  return steps.value.find(item => item.key === key);
};

const stepValueChange = (val: any, path: string[]) => {
  console.log("stepValueChange", val, path);
  const from = path[0];
  const to = path[path.length - 1];
  const valueName = activeStep.value.valueName || activeStep.value.key;
  // const nextStepDisabledKeys = activeStep.value.nextStepDisabledKeys;
  if (activeStep.value.dataType === "date") {
    const modelId = val?.length ? val[0] : "";
    const chooseStartDateStep = getStepByKey("chooseStartDate");
    const chooseEndDateStep = getStepByKey("chooseEndDate");

    chooseStartDateStep && (chooseStartDateStep.disabled = true);
    chooseEndDateStep && (chooseEndDateStep.disabled = true);

    if (modelId) {
      queryDate(modelId)
        .then(({ startDate, endDate }) => {
          chooseStartDateStep && (chooseStartDateStep.params!.defaultDate = startDate || "");
          chooseEndDateStep && (chooseEndDateStep.params!.defaultDate = endDate || "");
        })
        .finally(() => {
          chooseStartDateStep && (chooseStartDateStep.disabled = false);
          chooseEndDateStep && (chooseEndDateStep.disabled = false);
        });
    }
  }

  if (from === "chooseActualEnterprisePhase" && stepParams["chooseActualEnterprisePhase"]?.queryPhase) {
    const actualEnterprisePhaseModelId = val[0];
    if (actualEnterprisePhaseModelId) {
      archService.queryPhaseEndModel(projectId, actualEnterprisePhaseModelId).then(modelIds => {
        const chooseCapabilitiesStep = getStepByKey("chooseCapabilities");
        chooseCapabilitiesStep?.params && (chooseCapabilitiesStep.params.defaultRightSelectedIds = modelIds);
      });
    }
  }

  if (from === "chooseOwner") {
    const key = path[path.length - 1];
    result[key] = val;
    if (key === "ownerId") {
      activeStep.value.nextStepDisabled = !val;
    }
  } else if (to === "timeLine") {
    result["timeLineId"] = val;
  } else {
    result[valueName] = val;
  }
  // if (nextStepDisabledKeys) {
  //   nextStepDisabledKeys.forEach(key => {
  //     const currentStep = getStepByKey(key);
  //     let disabled = false;
  //     if (Array.isArray(val)) {
  //       disabled = !val.length;
  //     } else {
  //       disabled = !val;
  //     }
  //     if (currentStep) {
  //       currentStep.disabled = disabled;
  //     }
  //   });
  // }
  console.log("result", result);
};

const queryDate = async (modelId: string) => {
  const startDate = await archService.queryStartDateByInstance(projectId, modelId);
  const endDate = await archService.queryEndDateByInstance(projectId, modelId);
  return { startDate, endDate };
};

const updateStep = (num: number) => {
  let addNum = num;
  let nextStep = steps.value[currentStepIndex.value + addNum];
  while (nextStep.disabled) {
    addNum += num;
    nextStep = steps.value[currentStepIndex.value + addNum];
  }
  if (nextStep) {
    activeKey.value = nextStep.key;
  }
};

const handleSave = async () => {
  saveLoading.value = true;
  ipcWindowUtil.sendWindowChange({ success: true, result });
};

function handleclose(data: CloseData) {
  saveLoading.value = false;
  ipcWindowUtil.closeWindow(data);
  // emit('close', data);
  // remote.
}
function handleCancel() {
  handleclose({ success: false });
}
</script>
<style lang="scss">
.create-table-wizard-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
